import heapq


class Solution:
    def minCostConnectPoints(self, points: list) -> int:
        adj = [[] for _ in range(len(points))]
        for i in range(len(points)):
            for j in range(i + 1, len(points)):
                pointA = points[i]
                pointB = points[j]
                distance = abs(pointA[0] - pointB[0]) + abs(
                    pointA[1] - pointB[1])
                adj[i] += [(distance, j)]
                adj[j] += [(distance, i)]
        ans = 0
        visited = set()
        queue = [(0, 0)]
        heapq.heapify(queue)
        count = 0
        while queue:
            d, node = heapq.heappop(queue)
            if node not in visited:
                visited.add(node)
                ans += d
                count += 1
                for ne in adj[node]:
                    heapq.heappush(queue, ne)
            if count >= len(points):
                break
        return ans
